<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { $t } from '@/locales';
import { loginModuleRecord } from '@/constants/app';
import { useRouterPush } from '@/hooks/common/router';
import { useForm, useFormRules } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { ApiaccountserviceApi, ApiLoginInput } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import JSEncrypt from 'jsencrypt';

defineOptions({ name: 'PwdLogin' });

const authStore = useAuthStore();
const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useForm();

interface FormModel {
  account: string;
  passWord: string;
  verifyCode: string;
}

const model = reactive<ApiLoginInput>({
  account: '',
  passWord: '',
  verifyCode: '',
  verifyKey: ''
});

const verifyObj = reactive({
  verifyCodeKey: '',
  base64Src: ''
});

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale ref, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    account: formRules.userName,
    passWord: formRules.pwd,
    verifyCode: formRules.imgCode,
  };
});

const rsa_encrypt = (params: string, publicKey: string): string => {
  const Encrypt = new JSEncrypt();
  Encrypt.setPublicKey(publicKey);
  return Encrypt.encrypt(params) as string;
};

async function handleSubmit() {
  await validate();

  const loginObj = {
    ...model,
    // 密码加密
    passWord: rsa_encrypt(
      model.passWord,
      '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCru4GbB+SebAkZoTloake+25LRu9BDDMj8n4gELc1+60WfhUcQFljoOP2x6+QA/TnfROuiK8VbxM5ribHXN+b16Tv67DflZIKHva345RJOj9B9p9G3hiEHcGEHzYh3tT/bfLWuNyupiOJSdBFyEmWaWzhGNm29pI0FCcmkRzNA8wIDAQAB-----END PUBLIC KEY-----'
    ),
    verifyKey: verifyObj.verifyCodeKey
  }
  // 获取验证码key
  const [err, res] = await feature(getAPI(ApiaccountserviceApi).login(loginObj));
  if (err) {
    // 如果登录失败,刷新验证码
    handleGetVerifyCode();
  }
  queryDone(err, async () => {
    if (res?.data.data) {
      authStore.beforeLoginSuccess(res?.data.data);
    }
  });
}

const handleGetVerifyCode = async () => {
  // 获取验证码key
  const [err, res] = await feature(getAPI(ApiaccountserviceApi).getVerifyCode());
  queryDone(err, () => {
    if (res) {
      verifyObj.verifyCodeKey = res.data.verifyCodeKey!;
      verifyObj.base64Src = res.data.base64Src!;
    }
  });
};
onMounted(() => {
  handleGetVerifyCode();
});




</script>

<template>
  <ElForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <ElFormItem prop="account">
      <ElInput v-model="model.account" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </ElFormItem>
    <ElFormItem prop="passWord">
      <ElInput v-model="model.passWord" type="password" show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')" />
    </ElFormItem>
    <ElFormItem prop="verifyCode">
      <div class="w-full flex-y-center gap-16px">
        <ElInput v-model="model.verifyCode" size="large" :placeholder="$t('page.login.common.codePlaceholder')" />
        <img :src="verifyObj.base64Src" style="cursor: pointer" @click="handleGetVerifyCode" />
      </div>
    </ElFormItem>

    <ElSpace direction="vertical" :size="24" class="w-full" fill>
      <div class="flex-y-center justify-between">
        <ElCheckbox>{{ $t('page.login.pwdLogin.rememberMe') }}</ElCheckbox>
        <ElButton text @click="toggleLoginModule('reset-pwd')">
          {{ $t('page.login.pwdLogin.forgetPassword') }}
        </ElButton>
      </div>
      <ElButton type="primary" size="large" round block :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </ElButton>
      <!-- <div class="flex-y-center justify-between gap-12px">
        <ElButton class="flex-1" size="default" @click="toggleLoginModule('code-login')">
          {{ $t(loginModuleRecord['code-login']) }}
        </ElButton>
        <ElButton class="flex-1" size="default" @click="toggleLoginModule('register')">
          {{ $t(loginModuleRecord.register) }}
        </ElButton>
      </div> -->
      <!-- <ElDivider class="text-14px text-#666 !m-0">{{ $t('page.login.pwdLogin.otherAccountLogin') }}</ElDivider>
      <div class="flex-center gap-12px">
        <ElButton
          v-for="item in accounts"
          :key="item.key"
          size="default"
          type="primary"
          :disabled="authStore.loginLoading"
          @click="handleAccountLogin(item)"
        >
          {{ item.label }}
        </ElButton>
      </div> -->
    </ElSpace>
  </ElForm>
</template>

<style scoped></style>
